﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace laohan.Common.USB
{
    /// <summary>
    /// 
    /// </summary>
    public class USBMonitor
    {
        const int DBT_ConfigChangeCanceled = 0x0019;
        const int DBT_ConfigChanged = 0x0018;
        const int DBT_CustomEvent = 0x8006;
        const int DBT_DeviceQueryRemove = 0x8001;
        const int DBT_DeviceQueryRemoveFailed = 0x8002;
        const int DBT_DeviceRemovePending = 0x8003;
        const int DBT_DeviceTypeHanged = 0x8007;
        const int DBT_QueryChangSpecific = 0x8005;
        const int DBT_DevNodes_CEConfig = 0x0017;
        const int DBT_UserDefined = 0xFFFF;
        const int WM_DeviceChange = 0x219;   // 系统硬件改变发出的系统消息
        const int DBT_DeviceArrival = 0x8000;   // 设备检测结束，并可以使用
        const int DBT_DeviceRemoveComplete = 0x8004;// 设备移除

        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        public static void ListenUSB(Message m, Action<DriveInfo> action)
        {
            if (m.Msg == WM_DeviceChange) // 系统硬件改变发出的系统消息
            {
                switch (m.WParam.ToInt32())
                {
                    case WM_DeviceChange:
                        break;
                    case DBT_DeviceArrival:
                        ScanDisk(action); // 扫描所有满足特征的设备
                        break;
                    case DBT_DeviceRemoveComplete:
                        ScanDisk(action);
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void ScanDisk(Action<DriveInfo> action)
        {
            DriveInfo[] drives = DriveInfo.GetDrives();

            foreach (var drive in drives)
            {
                // 可移动存储设备，且不是A盘
                if ((drive.DriveType == DriveType.Removable) && false == drive.Name.Substring(0, 1).Equals("A"))
                {
                    action?.Invoke(drive);
                }
            }
        }
    }
}
